from rest_framework import viewsets, status
from rest_framework.decorators import action
from rest_framework.response import Response
from rest_framework.permissions import IsAuthenticated
from django_filters.rest_framework import DjangoFilterBackend
from rest_framework import filters
from django.db.models import Q
from common.viewsets import BaseModelViewSet
from common.response import APIResponse
from .models import Environment, HostType, HostGroup, Host
from .serializers import (
    EnvironmentSerializer, HostTypeSerializer, HostGroupSerializer,
    HostSerializer
)
from common.response import APIResponse

# 临时序列化器定义，直到创建完整的序列化器文件
class HostListSerializer(HostSerializer):
    class Meta(HostSerializer.Meta):
        fields = ['id', 'hostname', 'ip', 'status', 'host_type_name', 'environment_name']

class HostBatchOperationSerializer:
    def __init__(self, data=None):
        self.data = data
        self.validated_data = data

    def is_valid(self, raise_exception=False):
        return True
from monitoring.tasks import test_host_connectivity


class EnvironmentViewSet(BaseModelViewSet):
    """环境管理ViewSet"""
    queryset = Environment.objects.all().order_by('code')
    serializer_class = EnvironmentSerializer
    filter_backends = [DjangoFilterBackend, filters.SearchFilter, filters.OrderingFilter]
    filterset_fields = ['is_active']
    search_fields = ['name', 'code', 'description']
    ordering_fields = ['code', 'created_at']

    @action(detail=False, methods=['get'])
    def active(self, request):
        """获取激活的环境列表"""
        environments = self.queryset.filter(is_active=True)
        serializer = self.get_serializer(environments, many=True)
        return APIResponse.success(serializer.data)


class HostTypeViewSet(BaseModelViewSet):
    """主机类型管理ViewSet"""
    queryset = HostType.objects.all().order_by('code')
    serializer_class = HostTypeSerializer
    filter_backends = [DjangoFilterBackend, filters.SearchFilter, filters.OrderingFilter]
    filterset_fields = ['is_active']
    search_fields = ['name', 'code', 'description']
    ordering_fields = ['code', 'created_at']

    @action(detail=False, methods=['get'])
    def active(self, request):
        """获取激活的主机类型列表"""
        host_types = self.queryset.filter(is_active=True)
        serializer = self.get_serializer(host_types, many=True)
        return APIResponse.success(serializer.data)

    @action(detail=True, methods=['get'])
    def hosts(self, request, pk=None):
        """获取指定类型的主机列表"""
        host_type = self.get_object()
        hosts = Host.objects.filter(host_type=host_type, is_active=True)
        serializer = HostListSerializer(hosts, many=True)
        return APIResponse.success(serializer.data)


class HostGroupViewSet(BaseModelViewSet):
    """主机组管理ViewSet"""
    queryset = HostGroup.objects.all().order_by('code')
    serializer_class = HostGroupSerializer
    filter_backends = [DjangoFilterBackend, filters.SearchFilter, filters.OrderingFilter]
    filterset_fields = ['environment', 'type', 'status', 'is_active']
    search_fields = ['name', 'code', 'description']
    ordering_fields = ['code', 'created_at']

    @action(detail=False, methods=['get'])
    def active(self, request):
        """获取激活的主机组列表"""
        host_groups = self.queryset.filter(is_active=True)
        serializer = self.get_serializer(host_groups, many=True)
        return APIResponse.success(serializer.data)

    @action(detail=True, methods=['get'])
    def hosts(self, request, pk=None):
        """获取主机组下的主机列表"""
        host_group = self.get_object()
        hosts = Host.objects.filter(host_group=host_group, is_active=True)
        serializer = HostListSerializer(hosts, many=True)
        return APIResponse.success(serializer.data)

    @action(detail=True, methods=['post'])
    def toggle_load_balancer(self, request, pk=None):
        """切换负载均衡状态"""
        host_group = self.get_object()
        enabled = request.data.get('enabled', not host_group.load_balancer_enabled)
        host_group.load_balancer_enabled = enabled
        host_group.save(update_fields=['load_balancer_enabled'])

        return APIResponse.success({
            'enabled': enabled,
            'message': f"负载均衡已{'启用' if enabled else '禁用'}"
        })

    @action(detail=True, methods=['post'])
    def toggle_health_check(self, request, pk=None):
        """切换健康检查状态"""
        host_group = self.get_object()
        enabled = request.data.get('enabled', not host_group.health_check_enabled)
        host_group.health_check_enabled = enabled
        host_group.save(update_fields=['health_check_enabled'])

        return APIResponse.success({
            'enabled': enabled,
            'message': f"健康检查已{'启用' if enabled else '禁用'}"
        })


class HostViewSet(BaseModelViewSet):
    """主机管理ViewSet"""
    queryset = Host.objects.all().order_by('-created_at')
    serializer_class = HostSerializer
    filter_backends = [DjangoFilterBackend, filters.SearchFilter, filters.OrderingFilter]
    filterset_fields = ['host_type', 'environment', 'host_group', 'status', 'is_active', 'monitor_enabled']
    search_fields = ['hostname', 'ip', 'description', 'tags']
    ordering_fields = ['hostname', 'ip', 'created_at', 'last_heartbeat']

    def get_serializer_class(self):
        """根据action选择序列化器"""
        if self.action == 'list':
            return HostListSerializer
        return HostSerializer

    def get_queryset(self):
        """自定义查询集"""
        queryset = super().get_queryset()

        # 支持复杂搜索
        search = self.request.query_params.get('search', None)
        if search:
            queryset = queryset.filter(
                Q(hostname__icontains=search) |
                Q(ip__icontains=search) |
                Q(description__icontains=search) |
                Q(host_type__name__icontains=search) |
                Q(environment__name__icontains=search) |
                Q(host_group__name__icontains=search)
            )

        return queryset

    @action(detail=False, methods=['get'])
    def summary(self, request):
        """获取主机统计摘要"""
        total_hosts = self.queryset.filter(is_active=True).count()
        online_hosts = self.queryset.filter(is_active=True, status='online').count()
        offline_hosts = self.queryset.filter(is_active=True, status='offline').count()
        maintenance_hosts = self.queryset.filter(is_active=True, status='maintenance').count()
        error_hosts = self.queryset.filter(is_active=True, status='error').count()

        return APIResponse.success({
            'total_hosts': total_hosts,
            'online_hosts': online_hosts,
            'offline_hosts': offline_hosts,
            'maintenance_hosts': maintenance_hosts,
            'error_hosts': error_hosts,
            'online_percentage': round(online_hosts / total_hosts * 100, 1) if total_hosts > 0 else 0,
            'offline_percentage': round(offline_hosts / total_hosts * 100, 1) if total_hosts > 0 else 0
        })

    @action(detail=True, methods=['post'])
    def test_connection(self, request, pk=None):
        """测试主机连接"""
        host = self.get_object()
        test_type = request.data.get('test_type', 'all')

        # 异步执行连接测试
        task = test_host_connectivity.delay(host.id)

        return APIResponse.success({
            'task_id': task.id,
            'message': '连接测试已启动，请稍后查看结果'
        })

    @action(detail=False, methods=['post'])
    def batch_operation(self, request):
        """批量操作主机"""
        serializer = HostBatchOperationSerializer(data=request.data)
        serializer.is_valid(raise_exception=True)

        host_ids = serializer.validated_data['host_ids']
        operation = serializer.validated_data['operation']
        parameters = serializer.validated_data.get('parameters', {})

        hosts = Host.objects.filter(id__in=host_ids)

        if operation == 'enable':
            updated = hosts.update(is_active=True)
            message = f"已启用 {updated} 台主机"
        elif operation == 'disable':
            updated = hosts.update(is_active=False)
            message = f"已禁用 {updated} 台主机"
        elif operation == 'delete':
            deleted = hosts.delete()
            message = f"已删除 {deleted[0]} 台主机"
        elif operation == 'update_group':
            host_group_id = parameters.get('host_group_id')
            if host_group_id:
                updated = hosts.update(host_group_id=host_group_id)
                message = f"已更新 {updated} 台主机的主机组"
            else:
                return APIResponse.error("缺少主机组ID参数")
        else:
            return APIResponse.error("不支持的操作类型")

        return APIResponse.success({'message': message})

    @action(detail=True, methods=['post'])
    def toggle_monitoring(self, request, pk=None):
        """切换监控状态"""
        host = self.get_object()
        enabled = request.data.get('enabled', not host.monitor_enabled)
        host.monitor_enabled = enabled
        host.save(update_fields=['monitor_enabled'])

        return APIResponse.success({
            'enabled': enabled,
            'message': f"主机监控已{'启用' if enabled else '禁用'}"
        })

    @action(detail=True, methods=['post'])
    def update_status(self, request, pk=None):
        """更新主机状态"""
        host = self.get_object()
        new_status = request.data.get('status')

        if new_status not in ['online', 'offline', 'maintenance', 'error']:
            return APIResponse.error("无效的状态值")

        host.status = new_status
        host.save(update_fields=['status'])

        return APIResponse.success({
            'status': new_status,
            'message': f"主机状态已更新为 {new_status}"
        })
